<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useTradingAccountStore } from '@/stores/stock'
import {
  GetPlan,
  ListTransRecord,
  CreateTransRecord,
  DeleteTransRecord,
  UpdateTransRecord,
  SetPlanStatus,
} from '@/api/note'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

const store = useTradingAccountStore()
const route = useRoute()
const stockId = route.query.stockId
const planId = route.query.planId

const router = useRouter()

const planData = ref({})
const transRecords = ref([])

const dialog = reactive({
  transRecord: false,
  updateRecord: false,
})

const actionOptions = [
  {
    value: 1,
    label: '买',
  },
  {
    value: -1,
    label: '卖',
  },
]

let transRecordAddForm = reactive({})
let transRecordUpdateForm = reactive({})

// 页面初始化
onMounted(() => {
  if (store.currentTradingAccount.id) {
    init()
  }
})

const init = function () {
  reqPlan()
  reqTransRecord()
}

const reqPlan = function () {
  // 获取参数
  GetPlan(store.currentTradingAccount.id, stockId, planId).then((resp) => {
    if (resp.code === 0) {
      planData.value = resp.data
    }
  })
}
const reqTransRecord = function () {
  ListTransRecord(store.currentTradingAccount.id, stockId, planId).then((resp) => {
    if (resp.code === 0) {
      transRecords.value = resp.data
    }
  })
}

const finishPlan = function (id) {
  SetPlanStatus(store.currentTradingAccount.id, stockId, id, 1).then((resp) => {
    ElMessage.success(resp.msg)
    reqPlan()
  })
}

const addTransRecord = function () {
  CreateTransRecord(
    store.currentTradingAccount.id,
    stockId,
    planId,
    transRecordAddForm.date,
    transRecordAddForm.action,
    transRecordAddForm.price,
    transRecordAddForm.quantity,
    transRecordAddForm.reason,
  ).then((resp) => {
    if (resp.code === 0) {
      dialog.transRecord = false
      transRecordAddForm = reactive({})
      ElMessage.success(resp.msg)
      reqTransRecord()
    }
  })
}

const deleteTransRecord = function (id) {
  DeleteTransRecord(store.currentTradingAccount.id, stockId, planId, id).then((resp) => {
    if (resp.code === 0) {
      ElMessage.success(resp.msg)
      reqTransRecord()
    }
  })
}

const showUpdate = function (item) {
  dialog.updateRecord = true
  transRecordUpdateForm.id = item.id
  transRecordUpdateForm.action = item.action
  transRecordUpdateForm.price = item.price
  transRecordUpdateForm.quantity = item.quantity
  transRecordUpdateForm.reason = item.reason
}

const updateTransRecord = function () {
  UpdateTransRecord(
    store.currentTradingAccount.id,
    planData.value.id,
    transRecordUpdateForm.id,
    transRecordUpdateForm.action,
    transRecordUpdateForm.price,
    transRecordUpdateForm.quantity,
    transRecordUpdateForm.reason,
  ).then((resp) => {
    if (resp.code === 0) {
      dialog.updateRecord = false
      ElMessage.success(resp.msg)
      reqTransRecord()
      transRecordUpdateForm = reactive({})
    }
  })
}
</script>

<template>
  <div>
    <el-page-header
      style="margin-bottom: 23px"
      :icon="ArrowLeft"
      title="返回"
      @back="router.go(-1)"
    >
      <template #content>
        <el-text>Operate</el-text>
      </template>
    </el-page-header>

    <el-card class="header-card" shadow="never">
      <template #header>
        <div style="display: flex; flex-direction: row; justify-content: space-between">
          <div>
            <el-tag type="success"> {{ planData.code }} {{ planData.name }} </el-tag>
          </div>
          <div class="oper-btn" v-if="planData.status == 0">
            <el-button size="small" plain @click="finishPlan(planData.id)">完结</el-button>
          </div>
          <div v-else><el-tag size="small" type="danger">已完结</el-tag></div>
        </div>
      </template>

      <el-col>
        <el-text>
          止盈价格：{{ planData.takeProfitPrice }}
          <el-divider direction="vertical" />
          止损价格：{{ planData.stopLossPrice }}
        </el-text>
      </el-col>

      <el-col>
        <el-text>
          估值分析：<span v-for="(item, index) in planData.valuationAnalysis" :key="index">
            {{ item }} <el-divider direction="vertical" />
          </span>
        </el-text>
      </el-col>
    </el-card>

    <el-timeline style="max-width: 600px">
      <el-timeline-item v-if="planData.status == 0">
        <el-button @click="dialog.transRecord = true">添加操作</el-button>
      </el-timeline-item>
      <el-timeline-item
        v-for="(item, index) in transRecords"
        :key="index"
        center
        :timestamp="item.date"
        placement="top"
      >
        <el-card
          shadow="hover"
          :style="{ backgroundColor: trans.action == 1 ? '#e0efdf' : '#eabbd0' }"
          v-for="trans in item.trans"
          :key="trans.id"
          class="oper-card"
        >
          <template #header>
            <div style="display: flex; flex-direction: row; justify-content: space-between">
              <div>
                <el-tag v-if="trans.action == 1" type="success"> 买入</el-tag>
                <el-tag v-else type="danger"> 卖出</el-tag>
              </div>
              <div class="oper-btn" v-if="planData.status == 0">
                <el-button size="small" plain @click="showUpdate(trans)">编辑</el-button>
                <el-button size="small" plain @click="deleteTransRecord(trans.id)">删除</el-button>
              </div>
            </div>
          </template>
          <el-row>
            <el-text> 数量：{{ trans.quantity }}</el-text>
          </el-row>
          <el-row>
            <el-text> 价格：{{ trans.price }}</el-text>
          </el-row>
          <el-row>
            <el-text> 原因：{{ trans.reason }}</el-text>
          </el-row>
        </el-card>
      </el-timeline-item>
    </el-timeline>

    <!--    添加交易记录弹框   -->
    <el-dialog v-model="dialog.transRecord" title="添加" width="600">
      <el-form :model="transRecordAddForm">
        <el-form-item label="日期" label-width="60px">
          <el-date-picker
            style="width: 120px"
            v-model="transRecordAddForm.date"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="交易日期"
          />
        </el-form-item>
        <el-form-item label="动作" label-width="60px">
          <el-select
            v-model.number="transRecordAddForm.action"
            placeholder="买/卖"
            style="width: 120px"
          >
            <el-option
              v-for="item in actionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" label-width="60px">
          <el-input
            v-model.number="transRecordAddForm.price"
            style="width: 120px"
            type="number"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="数量" label-width="60px">
          <el-input
            v-model.number="transRecordAddForm.quantity"
            style="width: 120px"
            type="number"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="原因" label-width="60px">
          <el-input
            v-model="transRecordAddForm.reason"
            style="width: 400px"
            placeholder="请输入交易原因"
            type="textarea"
            :rows="3"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="addTransRecord">确认</el-button>
      </template>
    </el-dialog>

    <!--    更新交易记录弹框   -->
    <el-dialog v-model="dialog.updateRecord" title="Update Record" width="600">
      <el-form :model="transRecordUpdateForm">
        <el-form-item label="动作" label-width="60px">
          <el-select
            v-model.number="transRecordUpdateForm.action"
            placeholder="Select"
            style="width: 240px"
          >
            <el-option
              v-for="item in actionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" label-width="60px">
          <el-input v-model.number="transRecordUpdateForm.price" type="number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="数量" label-width="60px">
          <el-input
            v-model.number="transRecordUpdateForm.quantity"
            type="number"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="原因" label-width="60px">
          <el-input
            v-model="transRecordUpdateForm.reason"
            placeholder="请输入交易原因"
            type="textarea"
            :rows="3"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateTransRecord">Create</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped>
.header-card {
  margin-bottom: 23px;
}
.header-card:hover .oper-btn {
  visibility: visible;
}

.oper-card {
  margin-bottom: 5px;
}

.oper-btn {
  visibility: hidden;
}

.oper-card:hover .oper-btn {
  visibility: visible;
}
</style>
